<!--  -->
<template>
  <!-- 课堂管理 -->
  <div class='app-container'>
    <el-col :span="24" :xs="24">
      <el-form :model="tableParams" ref="queryForm" size="small" :inline="true" v-show="true" label-width="100px">
        <el-form-item label="课程分类编码" prop="code">
          <el-input v-model="tableParams.code" placeholder="请输入课程分类编码" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="课程分类名称" prop="name">
          <el-input v-model="tableParams.name" placeholder="请输入课程分类名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:user:add']">新增</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
      </el-row>
      <my-table :loading="loading" rowKey="id" :tableData="tableData" :params="tableParams">
        <el-table-column prop="classroomImages" label="课堂图片" align="center">
          <template slot-scope="scope">
            <viewer :images="[scope.row.classroomImages]">
              <img v-for="item in [scope.row.classroomImages]" :src="item" :key="item" alt="课堂图片"
                style="width: 100px; height: 60px;">
            </viewer>
          </template>
        </el-table-column>
        <el-table-column prop="classroomName" label="课堂名称" align="center">
        </el-table-column>
        <el-table-column prop="classroomIntroduction" label="课堂介绍" align="center">
        </el-table-column>
        <el-table-column prop="classroomLabels" label="课堂标签" align="center">
        </el-table-column>
        <el-table-column prop="classroomStatus" label="课堂状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.classroomStatus == 0" type="success">进行中</el-tag>
            <el-tag v-if="scope.row.classroomStatus == 1" type="warning">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="classroomType" label="课堂分类" align="center">
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)"
              v-hasPermi="['system:user:edit']">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)"
              v-hasPermi="['system:user:remove']">删除</el-button>
          </template>
        </el-table-column>
      </my-table>
    </el-col>
    <!-- 课程分类弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="55%" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" size="small" label-width="120px">
        <el-form-item label="课堂名称" prop="classroomName">
          <el-input type="text" placeholder="请输入课堂名称" v-model="dialogForm.classroomName"></el-input>
        </el-form-item>
        <el-form-item label="课堂图片" prop="classroomImages">
          <imageUpload v-model="dialogForm.classroomImages" :limit="1" :value="dialogForm.courseImages"></imageUpload>
        </el-form-item>
        <el-form-item label="课堂介绍" prop="classroomIntroduction">
          <el-input type="textarea" :rows="3" placeholder="请填写课堂介绍" v-model="dialogForm.classroomIntroduction"></el-input>
        </el-form-item>
        <el-form-item label="课堂标签" prop="classroomLabels">
          <el-select multiple placeholder="请选择课堂标签" v-model="dialogForm.classroomLabels">
            <el-option v-for="dict in dict.type.bus_course_lable" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课堂状态" prop="classroomStatus">
          <el-select placeholder="请选择课堂状态" v-model="dialogForm.classroomStatus">
            <el-option label="进行中" :value="0"></el-option>
            <el-option label="已完成" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课堂分类" prop="classroomType">
          <el-cascader placeholder="请选择课堂分类" v-model="dialogForm.classroomType"
            :props="{ children: 'list', value: 'code', label: 'name', checkStrictly: true }"
            :options="options"></el-cascader>
        </el-form-item>
        <el-form-item v-for="(item, index) in classroomChapter" :key="item.id" :label="`课程章节${index + 1}`">
          <el-input style="display: inline-block;width: 215px;" placeholder="请输入章节名称"
            v-model="item.name"></el-input>
          <i @click="addChapter" class="el-icon-circle-plus-outline"
            style="font-size: 20px;margin:0 5px;cursor: pointer;"></i>
          <el-popconfirm title="确定删除这个章节吗？" @confirm="delChapter(index)">
            <i slot="reference" v-if="index > 0" class="el-icon-delete-solid"
              style="font-size: 20px;color: orange;cursor: pointer;"></i>
          </el-popconfirm>
          <ul class="courseList">
            <li v-for="(it, idx) in item.courseId" :key="it+Math.random()">
              <el-select v-model="classroomChapter[index]['courseId'][idx]" placeholder="请选择课程">
                <el-option v-for="dict in courseOptions" :key="dict.courseId" :label="dict.courseName"
                  :value="dict.courseId" />
              </el-select>
              <span style="width: 46px;display: flex;justify-content: space-between;align-items: center;margin-left: 5px;">
                <i v-if="(item.courseId.length > 1 && idx == item.courseId.length - 1) || item.courseId.length == 1"
                  @click="addCourse(index)" class="el-icon-circle-plus-outline"
                  style="font-size: 20px;cursor: pointer;"></i>
                <el-popconfirm title="确定删除这个课程吗？" @confirm="delCourse(index, idx)">
                  <i slot="reference" v-if="idx > 0" class="el-icon-delete-solid"
                    style="font-size: 20px;color: orange;cursor: pointer;"></i>
                </el-popconfirm>
              </span>

            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getClassList, addClass, editClass, deleteClass } from '@/api/classManage/classApi';
import { getCourseTypeList } from '@/api/courseManage/courseType';
import { getCourseList } from '@/api/courseManage/courseManage';
import { getTreeIds } from '@/utils/utils';
export default {
  dicts: ['bus_course_lable'],
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      loading: false,
      tableData: [],//表格数据
      tableParams: {
        classroomName: "",
        pageNum: 1,
        pageSize: 10,
      },//表格参数
      dialogFormVisible: false,//弹窗显示隐藏
      classroomChapter: [{ 'classroomChapterId': 1, 'name': '', courseId: [] }],
      dialogForm: {
        classroomName: "",
        classroomImages: "",
        classroomIntroduction: "",
        classroomLabels: [],
        classroomStatus: 0,
        classroomType: "",
        classroomId: "",
        courseList: [],
      },//弹窗数据
      options: [], //级联选择数据
      courseOptions: [],//课程列表
      dialogTitle: '新增课堂',
      rules: {
        classroomName: [
          { required: true, message: '请输入课堂名称', trigger: 'blur' }
        ],
        classroomImages: [
          { required: true, message: '请上传课堂图片', trigger: 'blur' }
        ],
        classroomIntroduction: [
          { required: true, message: '请输入课堂介绍', trigger: 'blur' }
        ],
        classroomLabels: [
          { required: true, message: '请选择课堂标签', trigger: 'blur' }
        ],
        classroomStatus: [
          { required: true, message: '请选择课堂状态', trigger: 'blur' }
        ],
        classroomType: [
          { required: true, message: '请选择课堂分类', trigger: 'blur' }
        ],
      },
      submiting: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 获取课程分类选项
    getCourseTypeOptions() {
      getCourseTypeList().then(res => {
        if (res.code == 200) {
          this.options = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    //获取课程列表
    getCourseList() {
      let params = {
        pageNum: 1,
        pageSize: 9999,
      }
      getCourseList(params).then(res => {
        if (res.code == 200) {
          this.courseOptions = res.rows
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    //获取表格数据
    getList() {
      this.loading = true;
      getClassList(this.tableParams).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.tableData = res.rows;
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.loading = false;
      })
    },
    //添加章节
    addChapter() {
      this.classroomChapter.push({ 'classroomChapterId': this.classroomChapter.length + 1, 'name': '', courseId: [''] })
    },
    //添加课程
    addCourse(index) {
      this.classroomChapter[index].courseId.push('')
    },
    //删除章节
    delChapter(index) {
      this.classroomChapter.splice(index, 1)
    },
    //删除课程
    delCourse(index, idx) {
      this.classroomChapter[index].courseId.splice(idx, 1)
    },
    // 重置
    resetQuery() {
      this.tableData = [];
      this.tableParams.classroomName = "";
      this.tableParams.pageNum = 1;
      this.getList();
    },
    // 添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.dialogTitle = '新增课堂';
      this.dialogForm = {
        classroomName: "",
        classroomImages: "",
        classroomIntroduction: "",
        classroomLabels: [],
        classroomStatus: 0,
        classroomType: "",
        classroomId: "",
        courseList: [],
      }
      this.classroomChapter = [{ 'classroomChapterId': 1, 'name': '', courseId: [''] }]
    },
    //修改
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.dialogTitle = '编辑课堂';
      let courseLabels = row.classroomLabels.split(',');
      let pid = getTreeIds(this.options, row.classroomType, { children: 'list', id: 'code' })['ids'];
      console.log(pid);
      this.classroomChapter = this.covertData2(row.courseList);
      this.dialogForm = {
        classroomName: row.classroomName,
        classroomImages: row.classroomImages,
        classroomIntroduction: row.classroomIntroduction,
        classroomLabels: courseLabels,
        classroomStatus: row.classroomStatus,
        classroomType: pid,
        classroomId: row.classroomId,
        courseList: [],
      }
    },
    //将章节数据结构转换成后端需要的数据结构
    covertData(){
      let data = JSON.parse(JSON.stringify(this.classroomChapter));
      let result = [];
      data.map(item=>{
        item.courseId.map(it=>{
          result.push({
            classroomChapterId:item.classroomChapterId,
            name:item.name,
            courseId:it,
          })
        })
      })
      return result;
    },
    //将后端返回的章节数据转成前端需要的数据结构
    covertData2(data){
      let result = [];
      data.map(item=>{
        let index = result.findIndex(it=>it.classroomChapterId == item.classroomChapterId);
        if(index == -1){
          result.push({
            classroomChapterId:item.classroomChapterId,
            name:item.name,
            courseId:[item.courseId],
          })
        }else{
          result[index].courseId.push(item.courseId);
        }
      })
      return result;
    },
    //提交
    submitForm() {
      console.log(this.covertData());
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.submiting = true;
          let params = JSON.parse(JSON.stringify(this.dialogForm));
          params.classroomLabels = params.classroomLabels.toString();
          params.classroomType = params.classroomType.toString();
          params.courseList = this.covertData();
          if (this.dialogTitle == '新增课堂') {
            addClass(params).then(res => {
              this.submiting = false;
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.submiting = false;
            })
          } else {
            editClass(params).then(res => {
              this.submiting = false;
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.submiting = false;
            })
          }
        } else {
          return false;
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除该课堂？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteClass(row.classroomId).then(res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success(res.msg);
            this.getList();
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          console.log(err);
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    cancel() {
      this.dialogFormVisible = false;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getCourseTypeOptions();
    this.getCourseList();
    this.getList();
  },
  beforeCreate() { }, //生命周期 - 创建之前
  beforeMount() { }, //生命周期 - 挂载之前
}
</script>
<style lang="scss" scoped>
.courseList {
  margin: 0;
  padding: 0;
  list-style-type: none;
  display: flex;
  flex-wrap: wrap;

  li {
    margin: 5px 10px 5px 0;
    display: flex;
    align-items: center;
    i{
      line-height:normal ;
    }
  }
}
</style>
